package com.baidu.mpks.security;


import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

@Component
public class MenuProcessor {
    private static final Logger log = LoggerFactory.getLogger(MenuProcessor.class);
    private Map<String, List<String>> permission2MenuListMap = new LinkedHashMap();

    public MenuProcessor() throws IOException {
        List<String> lines = IOUtils.readLines(this.getClass().getClassLoader().getResourceAsStream("config/menu_permission_matrix.properties"), Charset.forName("utf-8"));
        Iterator var2 = lines.iterator();

        while(var2.hasNext()) {
            String line = (String)var2.next();
            String[] strs = line.split("\t");
            String permission = strs[0];
            String[] menus = strs[1].split(",");
            this.permission2MenuListMap.put(permission, Arrays.asList(menus));
        }

        int menuCount = 0;
        log.info("matrix size: {}, {}", this.permission2MenuListMap.size(), Integer.valueOf(menuCount));
    }

    public Map<String, String> getCurrentUserMenus() {
        Subject subject = SecurityUtils.getSubject();
        Map<String, String> menus = new HashMap();
        String[] permissions = (String[])this.permission2MenuListMap.keySet().toArray(new String[0]);
        boolean[] permitteds = subject.isPermitted(permissions);

        for(int i = 0; i < permissions.length; ++i) {
            if (permitteds[i]) {
                Iterator var6 = ((List)this.permission2MenuListMap.get(permissions[i])).iterator();

                while(var6.hasNext()) {
                    String s = (String)var6.next();
                    menus.put(s, "1");
                }
            }
        }

        return menus;
    }
}
